<template>
	<!-- 搜索内容 -->
	<el-card>
		<el-form :model="searchWorkorderForm" inline>
			<el-form-item label="工单编码" style="width:240px">
				<el-input v-model="searchWorkorderForm.prouctionOrderCode" placeholder="工单编码"/>
			</el-form-item>
			<el-form-item label="工单名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.prouctionOrderName" placeholder="工单名称"/>
			</el-form-item>
			<el-form-item label="来源单据" style="width:240px">
        <el-select
            v-model="searchWorkorderForm.productionOrderSource"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="来源单据"
            style="width: 240px"
        >
          <el-option label="客户订单" value="1"/>
          <el-option label="库存订阅" value="2"/>
        </el-select>
			</el-form-item>
			<el-form-item label="产品编号" style="width:240px">
				<el-input v-model="searchWorkorderForm.materialCode"/>
			</el-form-item>
			<el-form-item label="产品名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.materialName"/>
			</el-form-item>
			<el-form-item label="客户编码" style="width:240px">
				<el-input v-model="searchWorkorderForm.customerCode"/>
			</el-form-item>
			<el-form-item label="客户名称" style="width:240px">
				<el-input v-model="searchWorkorderForm.customerName"/>
			</el-form-item>
			<el-form-item label="工单类型" style="width:240px">
        <el-select
            v-model="searchWorkorderForm.productionOrderType"
            filterable
            allow-create
            default-first-option
            :reserve-keyword="true"
            placeholder="来源单据"
            style="width: 240px"
        >
          <el-option label="自产" value="1"/>
          <el-option label="外协" value="2"/>
          <el-option label="外购" value="3"/>
        </el-select>
			</el-form-item>
			<el-form-item label="需求日期" style="width:240px">
				<el-date-picker
				        v-model="searchWorkorderForm.requestDate"
				        type="date"
				        placeholder="需求日期"
				        :disabled-date="disabledDate"
				        :shortcuts="shortcuts"
				        :size="size"
				      />
			</el-form-item>
			<!-- 操作功能:搜索与重置表单 -->
			<el-form-item>
				<el-button size="small" type="info" @click="handleSearchWorkorder">搜索工单</el-button>
				<el-button size="small" type="primary" @click="handleRestWorkorder">重置工单</el-button>
			</el-form-item>
		</el-form>
		<el-button size="default" @click="handleAddWorkorder" type="success">添加工单</el-button>
  </el-card>

  <el-card>
		<el-card>
			<el-table
			:data="workorderList"
			border
			stripe
			@selection-change="handleSelectionChange"
			>
				<el-table-column property="productionOrderCode" label="工单编码"></el-table-column>
				<el-table-column property="productionOrderName" label="工单名称"></el-table-column>
				<el-table-column property="productionOrderType" label="工单类型">
					<template #default="scope">
						{{scope.row.productionOrderType === 1 ? '自产' :
						scope.row.productionOrderType === 2 ? '外协' : '外购' }}
					</template>
        		</el-table-column>
				<el-table-column property="productionOrderSource" label="工单来源">
					<template #default="scope">
						{{scope.row.productionOrderSource === 1 ? '客户订单' : '库存备货' }}
					</template>
        		</el-table-column>
				<el-table-column property="orderCode" label="订单编号"></el-table-column>
				<el-table-column property="materialCode" label="产品编号"></el-table-column>
				<el-table-column property="material.name" label="产品名称"></el-table-column>
				<el-table-column property="material.unit.specification" label="规格型号"></el-table-column>
				<el-table-column property="material.unit.name" label="单位"></el-table-column>
				<el-table-column property="productionOrderQuantity" label="工单数量"></el-table-column>
				<el-table-column property="prouctionOrderCode" label="调整数量"></el-table-column>
				<el-table-column property="producedQuantity" label="已生产数量"></el-table-column>
				<el-table-column property="customerCode" label="客户编码"></el-table-column>
				<el-table-column property="customer.name" label="客户名称"></el-table-column>
				<el-table-column property="requestDate" label="需求日期"></el-table-column>
				<el-table-column property="status" label="单据状态">
          <template #default="scope">
            {{scope.row.status === 1 ? '草稿' :
              scope.row.status === 2 ? '已确认' : '已审核' }}
          </template>
        </el-table-column>

				<el-table-column fixed="right" label="操作" min-width="120">
					<template #default="scope">
            <!--根据状态(status)显示操作 草稿状态可以编辑（可以将状态修改成已确认）可以删除  已经确认 （可以修改成已审核）不能删除   已审核不能删除与编-->


            <el-button v-if="scope.row.status===1 ||scope.row.status===2"
                       link type="primary"
                       size="small"
                       @click="handleWorkorderEdit(scope.row)">
              编辑
            </el-button>
            <el-button v-if="scope.row.status===1 ||scope.row.status===2"
                       plain
                       link type="primary"
                       size="small"
                       @click="handleWorkorderChangeStatus(scope.row)">
              {{scope.row.status === 1 ? '确认工单' : '审核工单' }}
            </el-button>

						<el-button v-if="scope.row.status===1"
                       link type="danger"
                       size="small"
                       @click="handleDeleteWorkorder(scope.row)">
              删除
            </el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
	</el-card>

  <!-- 分页信息 -->
  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 添加工单弹窗 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="1200">
    <el-form :model="dialogWorkorderList" inline>
      <el-form-item label="工单编码" style="width:240px">
        <el-input v-model="dialogWorkorderList.productionOrderCode" />
      </el-form-item>
      <el-form-item label="工单名称" style="width:240px">
        <el-input v-model="dialogWorkorderList.productionOrderName" />
      </el-form-item>
      <el-form-item label="工单类型" style="width:240px">
        <el-select
          v-model="dialogWorkorderList.productionOrderType"
          filterable
          allow-create
          default-first-option
          :reserve-keyword="true"
          placeholder="请选择工单类型"
          style="width: 240px"
        >
          <el-option label="自产" value="1"/>
          <el-option label="外协" value="2"/>
          <el-option label="外购" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="工单来源" style="width:240px">
        <el-select
          v-model="dialogWorkorderList.productionOrderSource"
          filterable
          allow-create
          default-first-option
          :reserve-keyword="false"
          placeholder="请选择工单来源"
          style="width: 240px"
        >
          <el-option label="客户订单" value="1"/>
          <el-option label="库存订阅" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" style="width:240px" v-if="dialogWorkorderList.productionOrderSource === '1'">
        <el-input v-model="dialogWorkorderList.orderCode" />
      </el-form-item>
      <el-form-item label="产品编号" style="width:240px">
        <el-input v-model="dialogWorkorderList.materialCode" />
      </el-form-item>
      <el-form-item label="产品编号" style="width:240px">
        <el-button size="default" type="info" @click="handleOpenMaterialSearch('workorder')">搜索</el-button>
      </el-form-item>


      <el-form-item label="工单数量" style="width:240px">
        <el-input v-model="dialogWorkorderList.productionOrderQuantity" />
      </el-form-item>
      <el-form-item label="需求日期" style="width:240px">
        <el-date-picker
          v-model="dialogWorkorderList.requestDate"
          type="date"
          placeholder="请选择需求日期"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="客户编码" style="width:240px">
        <el-input v-model="dialogWorkorderList.customerCode" />
      </el-form-item>
      <el-form-item label="客户编码" style="width:240px">
        <el-button size="default" type="info" @click="handleCustomerSearch">搜索</el-button>
      </el-form-item>
      <el-form-item label="供应商编码" style="width:240px" v-if="dialogWorkorderList.productionOrderType !== '1'">
        <el-input v-model="dialogWorkorderList.supplierCode" />
      </el-form-item>
	  <el-form-item label="供应商编码" style="width:240px" v-if="dialogWorkorderList.productionOrderType !== '1'">
       <el-button size="default" type="info" @click="handleSupplierSearch">搜索</el-button>
      </el-form-item>
      <el-form-item label="备注" style="width:240px">
        <el-input v-model="dialogWorkorderList.remark" />
      </el-form-item>
    </el-form>

    <!-- TODO BOM组成表格 - 仅在编辑模式下显示 -->
    <el-card v-if="isEditMode" class="bom-card">
      <template #header>
        <div class="card-header">
          <p> BOM组成</p>
          <el-button type="primary" size="small" @click="handleAddBom">添加物料</el-button>
          <el-button type="danger" size="small" @click="handleDeleteBom">删除物料</el-button>
        </div>
      </template>

      <el-table :data="BomSearchList" style="width: 100%" border @selection-change="handleBomSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编码" width="120" />
        <el-table-column prop="requiredQuantity" label="物料名称" width="150" />
        <el-table-column prop="issuedQuantity" label="需求数量" width="100" />
        <el-table-column prop="unitUsage" label="用量单位" width="80" />
        <el-table-column prop="unit.name" label="单位" width="80" />
        <el-table-column prop="sortOrder" label="单位" width="80" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" size="small"  @click="handleGetBomById(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDeleteBom(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页栏 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="Bompagination.currentPage"
            v-model:page-size="Bompagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="Bompagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleBomSizeChange"
            @current-change="handleBomCurrentChange"
        />
      </div>

    </el-card>



    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormClean">Cancel</el-button>
        <el-button type="primary" @click="handladdWorkorderdialog">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>


  <!--用户信息-->
  <el-dialog v-model="customerDialogFormVisible" title="客户列表" width="1200" center>
    <!-- 列表 -->
    <el-card class="table-card">
      <el-table
          :data="customerList"
          border
          stripe
          @selection-change="handleSelectionChange"
      >
        <el-table-column label="选择" width="60">
        <template #default="{ row }">
          <el-radio v-model="selectedCustomerId" :label="row.id" @change="handleCustomerSelect(row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="客户编号" />
        <el-table-column prop="name" label="客户名" />
        <el-table-column prop="address" label="客户地址" />
        <el-table-column prop="contactPerson" label="联系人" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="fax" label="传真" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'">
              {{ scope.row.status == '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页栏 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="Customerpagination.currentPage"
          v-model:page-size="Customerpagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="Customerpagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleCustomerSizeChange"
          @current-change="handleCustomerCurrentChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="customerDialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleCustomerSelect">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 供应商弹窗 -->
  <el-dialog v-model="supplierDialogFormVisible" title="Shipping address" width="1200">
    <!-- 列表 -->
    <el-card class="table-card">
      <el-table
          :data="supplierList"
          border
          stripe
          @selection-change="handleSelectionChange"
      >
        <el-table-column label="选择" width="60">
          <template #default="{ row }">
            <el-radio v-model="selectedCustomerId" :label="row.id" @change="handleSupplierSelect(row)">
              <span></span>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="供应商编号" />
        <el-table-column prop="name" label="供应商名" />
        <el-table-column prop="address" label="供应商地址" />
        <el-table-column prop="contactPerson" label="联系人" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="fax" label="传真" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'">
              {{ scope.row.status == '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页栏 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="supplierpagination.currentPage"
          v-model:page-size="supplierpagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="supplierpagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="supplierDialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="supplierDialogFormVisible = false">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 物料选择弹窗 -->
  <el-dialog title="选择物料" v-model="materialSelectDialogVisible" width="90%" :close-on-click-modal="false">
    <!-- 物料列表 -->
    <el-table
        :data="materialList"
        @selection-change="handleMaterialSelectionChange"
        border
        stripe>

      <el-table-column label="选择" width="80" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleMaterialSelectionChange(scope.row)">选择</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="物料编号" width="150" show-overflow-tooltip />
      <el-table-column prop="name" label="物料名称" width="200" show-overflow-tooltip />
      <el-table-column prop="specification" label="规格型号" width="180" show-overflow-tooltip />
      <el-table-column label="单位" width="100" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.unit?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="分类" width="120" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.category?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
      <el-table-column label="库存状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.hasSafetyStock ? 'success' : 'warning'">
            {{ scope.row.hasSafetyStock ? '有库存' : '无库存' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center;">
      <el-pagination
          v-model:current-page="materialPagination.currentPage"
          v-model:page-size="materialPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="materialPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMaterialSizeChange"
          @current-change="handleMaterialCurrentChange"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="materialSelectDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- TODO 弹窗 -->
  <el-dialog v-model="dialogBomFormVisible" :title="isBomEditMode?'更新BOM组成':'添加Bom组成'" width="800">
    <el-form :model="form" inline>
      <el-form-item label="物料编码" style="width:240px">
        <el-input v-model="BomForm.materialCode"/>
      </el-form-item>
      <el-form-item style="width:100px">
        <el-button size="default" type="default" @click="handleOpenMaterialSearch('bom')">搜索物料</el-button>
      </el-form-item>

      <el-form-item label="需求量" style="width:240px">
        <el-input v-model="BomForm.requiredQuantity"/>
      </el-form-item>
      <el-form-item label="生产量" style="width:240px">
        <el-input v-model="BomForm.issuedQuantity"/>
      </el-form-item>
      <el-form-item label="用量" style="width:240px">
        <el-input v-model="BomForm.unitUsage"/>
      </el-form-item>
      <el-form-item label="排序" style="width:240px">
        <el-input v-model="BomForm.sortOrder"/>
      </el-form-item>
      <el-form-item label="备注" style="width:240px">
        <el-input v-model="BomForm.remark"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogBomFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSumbitAdd">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>




</template>

<script setup>
	import { onMounted,reactive, ref } from 'vue';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import {getProductionOrderList,addProductionOrder,updateProductionOrder,updateProductionOrderStatus,deleteProductionOrder} from "@/api/production-order-api.js";
  import {getCustomerPage} from "@/api/customer.js";
  import {getSupplierPage} from "@/api/supplier.js";
  import { getMaterialPage } from "@/api/material.js";
  import {
    getProductionOrderBomList, addProductionOrderBom, updateProductionOrderBom, batchDeleteProductionOrderBom,
    getProductionOrderBomById
  } from "@/api/ProductionOrderBom.js";

  //弹窗设置
  const dialogFormVisible = ref(false);
  const dialogTitle = ref("");
  const isEditMode = ref(false); // 区分添加/编辑模式

	const searchWorkorderForm = ref({
		prouctionOrderCode:"",
		prouctionOrderName:"",
		productionOrderSource:"",
		materialCode:"",
		materialName:"",
		customerCode:"",
		customerName:"",
		productionOrderType:"",
		requestDate:"",
	});

  const handleRestWorkorder = () => {
    // 重置搜索表单所有字段
    searchWorkorderForm.value = {
      prouctionOrderCode: "",
      prouctionOrderName: "",
      productionOrderSource: "",
      materialCode: "",
      materialName: "",
      customerCode: "",
      customerName: "",
      productionOrderType: "",
      requestDate: "",
    };
    handleSearchWorkorder();
  }

  const handleWorkorderChangeStatus = (row) => {
    ElMessageBox.confirm(
        row.status === 1 ? '确认工单吗？' : '审核通过吗？',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          handleChange(row);
          handleSearchWorkorder();
        })

  }

  const handleChange = (row) => {
    let status = row.status==1?2:3;
    console.log(row);
    updateProductionOrderStatus(row.id,status).then(res => {
      ElMessage({
        type: 'success',
        message: res.msg,
      })
    });
  }


	// 分页数据
	const pagination = ref({
	  currentPage: 1,
	  pageSize: 10,
	  total: 0
	});

	// 数据表单
	const workorderList = ref([]);

	//搜索表单
	const handleSearchWorkorder = () =>{
		const queryParams = {
			page: pagination.value.currentPage,
			pageSize: pagination.value.pageSize,
			...searchWorkorderForm.value
   		 };

		getProductionOrderList(queryParams).then(res=>{
			workorderList.value = res.data.list;
			pagination.value.total = res.data.total;
		});
	}

	// 改变分页大小
	const handleSizeChange = (newSize) =>{
		pagination.value.pageSize = newSize;
		pagination.value.currentPage = 1;
		handleSearchWorkorder();
	}

	// 改变当前页码
	const handleCurrentChange =(newPage)=>{
		pagination.value.currentPage = newPage;
		handleSearchWorkorder();
	}

	// 选中项
	const selectedWorkflows = ref([]);

	// 处理选中项变化
	const handleSelectionChange = (selection) => {
		selectedWorkflows.value = selection;
    handleSearchWorkorder();
	}

  const handleDeleteWorkorder =(row)=>{
    console.log(row);
    deleteProductionOrder(row.id);
    handleSearchWorkorder();
  }


	// 添加工单弹窗
	const handleAddWorkorder = () => {
		isEditMode.value = false; // 设置为添加模式
		dialogTitle.value = '添加工单';
		dialogFormVisible.value = true;

		// 清空表单数据
		Object.assign(dialogWorkorderList, {
			id: "",
			productionOrderCode: "",
			productionOrderName: "",
			productionOrderType: "",
			productionOrderSource: "",
			orderCode: "",
			materialCode: "",
			productionOrderQuantity: "",
			customerCode: "",
			supplierCode: "",
			requestDate: "",
			status: "",
			qrCodeUrl: "",
			parentId: "",
			remark: "",
		});
	}





	// 弹窗信息显示
	const dialogWorkorderList = reactive({
		id: "",
		productionOrderCode: "",
		productionOrderName: "",
		productionOrderType: "",
		productionOrderSource: "",
		orderCode: "",
		materialCode: "",
		productionOrderQuantity: "",
		producedQuantity: "",
		customerCode: "",
		supplierCode: "",
		requestDate: "",
		status: "",
		qrCodeUrl: "",
		parentId: "",
		remark: "",
		createTime: "",
		updateTime: "",
		creatorId: "",
		deleteFlag: ""
	});

  const customerDialogFormVisible =ref(false);

  //清空表单
  const dialogFormClean =()=>{
    dialogFormVisible.value = false;
    dialogWorkorderList.value = null;
  }

  // 获取对应的工单信息
  const handleWorkorderEdit = (row) => {
    isEditMode.value = true; // 设置为编辑模式
    dialogTitle.value = '编辑工单';
    dialogFormVisible.value = true;

    // 填充表单数据，过滤掉 null 和 undefined 值
    const filteredData = {};
    Object.keys(row).forEach(key => {
      // 只复制非空值，空值保持原有的空字符串
      if (row[key] !== null && row[key] !== undefined) {
        filteredData[key] = row[key];
      }
    });
    console.log("=================================")
    console.log(isEditMode.value);

    if(isEditMode.value) {
      BomForm.productionOrderId=row.id;
      console.log(BomForm.productionOrderId);
      handleBomSearch(row);



    }
    Object.assign(dialogWorkorderList, filteredData);

    console.log('编辑工单原始数据:', row);
    console.log('编辑工单过滤后数据:', filteredData);
  }

  // 提交添加/编辑信息
  const handladdWorkorderdialog = () => {
    // 处理提交数据，避免外键约束错误
    const submitData = { ...dialogWorkorderList };

    // 如果是自制类型(值为'1')，删除供应商编码字段
    if (submitData.productionOrderType === '1') {
      delete submitData.supplierCode;
    }

    // 如果供应商编码为空字符串，也删除该字段
    if (submitData.supplierCode === '') {
      delete submitData.supplierCode;
    }

    // 根据模式调用不同的API
    const apiCall = isEditMode.value ? updateProductionOrder(submitData) : addProductionOrder(submitData);
    const successMessage = isEditMode.value ? "更新成功" : "添加成功";
    const errorMessage = isEditMode.value ? "更新失败" : "添加失败";

    apiCall.then(res => {

      ElMessage.success(successMessage);
      dialogFormVisible.value = false;
      handleSearchWorkorder(); // 刷新列表
    }).catch(err => {

      ElMessage.error(errorMessage);
    });
  }

  // 用户表单
  const customerForm = reactive({
    id: '',
    code: '',
    email: '',
    name: '',
    status: '',
    contactPerson:'',
    phone:'',
    fax:'',
    address:'',
    description:''
  })

  //客户分页信息
  const Customerpagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 改变客户分页大小
  const handleCustomerSizeChange = (newSize) =>{
    Customerpagination.pageSize = newSize;
    Customerpagination.currentPage = 1;
    handleCustomerSearch();
  }

  // 改变客户当前页码
  const handleCustomerCurrentChange =(newPage)=>{
    Customerpagination.currentPage = newPage;
    handleCustomerSearch();
  }

  // 获取客户列表
  const customerList = ref([]);

  const selectedCustomerId = ref(null);

  //获取客户列表
  const handleCustomerSearch =()=>{
    customerDialogFormVisible.value =true;
    //数据绑定
    getCustomerPage(Customerpagination.currentPage,Customerpagination.pageSize,null).then(res=>{
      customerList.value=res.data.list;
      Customerpagination.total = res.data.total;
    })
  }
  //将选择的客户信息回填到表中
  const handleCustomerSelect = (row) => {
    dialogWorkorderList.customerCode = row.code;
    console.log(row);
    customerDialogFormVisible.value = false;
  }


  // ============供应商信息============
  const supplierDialogFormVisible =ref(false);

  // 用户列表数据
  const supplierList = ref([]);

  //供应商分页信息
  const supplierpagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 改变页面大小
  const handleSupplierSizeChange = (newSize) =>{
    supplierpagination.pageSize = newSize;
    supplierpagination.currentPage = 1;
    handleSupplierSearch();
  }

  // 改变当前页码
  const handleSupplierCurrentChange =(newPage)=>{
    supplierpagination.currentPage = newPage;
    handleSupplierSearch();
  }
  const handleSupplierSelect = (row) => {
    dialogWorkorderList.supplierCode = row.code;
  }
  // 供应商搜索
  const handleSupplierSearch =()=>{
    supplierDialogFormVisible.value = true;

    getSupplierPage(pagination.currentPage, pagination.pageSize, null).then(res=>{
      supplierList.value = res.data.list;
      supplierpagination.total = res.data.total;
    })
  }


  // ============物料信息============
  const materialSelectDialogVisible = ref(false);

  const materialList = reactive([]);


  const materialSelectTarget = ref('workorder');

  // 物料分页
  const materialPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 改变页面大小
  const handleMaterialSizeChange = (newSize) =>{
    materialPagination.pageSize = newSize;
    materialPagination.currentPage = 1;
    handleMaterialSearch();
  }

  // 改变当前页码
  const handleMaterialCurrentChange =(newPage)=>{
    materialPagination.currentPage = newPage;
    handleMaterialSearch();
  }

  // 打开物料搜索并标记目标
  const handleOpenMaterialSearch = (target) => {
    materialSelectTarget.value = target; // 'workorder' | 'bom'
    handleMaterialSearch();
  }

  // 选择物料
  const handleMaterialSelectionChange = (row) => {
    // 兼容 selection-change(数组) 与 行内按钮(对象)
    if (Array.isArray(row)) return;
    if (!row) return;

    if (materialSelectTarget.value === 'bom') {
      BomForm.materialCode = row.code;
    } else {
      dialogWorkorderList.materialCode = row.code;
      dialogWorkorderList.materialName = row.name;
    }
    materialSelectDialogVisible.value = false;
  }

  const handleMaterialSearch = () => {
    materialSelectDialogVisible.value = true;

    getMaterialPage(materialPagination.currentPage, materialPagination.pageSize, null).then(res => {
      console.log(res.data.list);
      // 修复 reactive 数组赋值
      materialList.splice(0, materialList.length, ...res.data.list);
      materialPagination.total = res.data.total;
    }).catch(err => {
      console.error('获取物料数据失败:', err);
    });
  }

  // =========================Bom===========================

  //供应商分页信息
  const Bompagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 改变页面大小
  const handleBomSizeChange = (newSize) =>{
    Bompagination.pageSize = newSize;
    Bompagination.currentPage = 1;
    handleBomSearch();
  }

  // 改变当前页码
  const handleBomCurrentChange =(newPage)=>{
    Bompagination.currentPage = newPage;
    handleBomSearch();
  }

  //弹窗开关
  const dialogBomFormVisible = ref(false);

  const resetBomForm = () => {
    const keepProductionOrderId = BomForm.productionOrderId || '';
    Object.assign(BomForm, {
      id: '',
      productionOrderId: keepProductionOrderId,
      materialCode: '',
      requiredQuantity: '',
      issuedQuantity: '',
      unitUsage: '',
      unitNmae: '',
      sortOrder: '',
      remark: ''
    });
  }

  const handleAddBom = () => {
    isBomEditMode.value = false;
    resetBomForm();
    dialogBomFormVisible.value = true;
  }


  const BomSearchList = ref([]);

  const currentSelectedRow = ref(null); // 保存当前选中的生产工单

  // 定义bom信息
  const BomForm = reactive({
    id:"",
    productionOrderId:"",
    materialCode:"",
    requiredQuantity:"",
    issuedQuantity:"",
    unitUsage:"",
    unitNmae:"",
    sortOrder:"",
    remark:""
  })

  const isBomEditMode = ref(false);
  // BOM 表格选择项，用于批量删除
  const bomSelectedRows = ref([]);
  const handleBomSelectionChange = (selection) => {
    bomSelectedRows.value = selection || [];
  }

  // 删除BOM（支持单条与批量）——仅使用 batchDeleteProductionOrderBom
  const handleDeleteBom = async (row) => {
    try {
      // 行内删除：优先使用传入行
      if (row && row.id) {
        await ElMessageBox.confirm('确认删除该物料吗？', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const idsStr = `ids=${row.id}`;
        const res = await batchDeleteProductionOrderBom(idsStr);
        ElMessage.success(res?.msg || '删除成功');
        handleBomSearch();
        return;
      }

      // 批量删除：使用已选择的多行
      if (!bomSelectedRows.value.length) {
        ElMessage.warning('请先选择要删除的物料');
        return;
      }
      await ElMessageBox.confirm(`确认删除选中的 ${bomSelectedRows.value.length} 条物料吗？`, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });
      const idsStr = `ids=${bomSelectedRows.value.map(r => r.id).join(',')}`;
      const res = await batchDeleteProductionOrderBom(idsStr);
      ElMessage.success(res?.msg || '删除成功');
      handleBomSearch();
    } catch (e) {
      // 用户取消或请求失败时无需额外处理
    }
  }

  // 加载Bom列表
  const handleBomSearch =(row)=>{
    if (row) {
      currentSelectedRow.value = row; // 保存当前选中的行
    }

    const targetRow = row || currentSelectedRow.value;
    if (!targetRow || !targetRow.id) {
      console.warn('没有选中的生产工单');
      return;
    }

    // 获取bom列表
    getProductionOrderBomList(targetRow.id, Bompagination.currentPage, Bompagination.pageSize).then(res=>{
      console.log("================");
      console.log(res.data.list);
      BomSearchList.value = res.data.list;
      Bompagination.total = res.data.total;
    }).catch(err => {
      console.error('获取BOM数据失败:', err);
    })
  }

  // 提交Bom组成
  const handleSumbitAdd = () => {
    const apiFn = isBomEditMode.value ? updateProductionOrderBom : addProductionOrderBom;
    const successMessage = isBomEditMode.value ? '更新成功' : '添加成功';
    const errorMessage = isBomEditMode.value ? '更新失败' : '添加失败';

    apiFn(BomForm).then(res => {
      if (res.code == 200) {
        ElMessage.success(successMessage);
        dialogBomFormVisible.value = false;
        resetBomForm();
        handleBomSearch();
      } else {
        ElMessage.error(errorMessage);
      }
    }).catch(() => {
      ElMessage.error(errorMessage);
    });
  }


  // 根据id获取对应的bom信息
  const handleGetBomById = (row) => {
    isBomEditMode.value = true;
    getProductionOrderBomById(row.id).then(res => {
      const d = res.data;
      if (d) Object.assign(BomForm, d);
      dialogBomFormVisible.value = true;
    });
  }



  onMounted(() => {
    handleSearchWorkorder();
  });
</script>

<style>

</style>